<?php
declare ( strict_types = 0 );
namespace app\controller;

use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use app\model\CatModel;
use app\model\UserModel;
use app\model\GoodsModel;
use app\model\WhModel;
use app\Common;
use app\controller\Token;

//Wh控制器

class Wh {
    //常用数据表内容 及常用字典
    var $cats = [];
    var $dept = [];
    var $users = [];
    var $goods = [];
    var $wh = [];
    var $status = array( '1'=>'待审核', '2'=>'已审核' );
    var $type = array( '1'=>'入库单', '2'=>'出库单', '3'=>'盘点单' );
    var $back = '<script>setTimeout(function(){history.back();},3000)</script>';

    public function __construct() {
        $gm = new GoodsModel();
        $this->goods = $gm->getAll(1);
        $cm = new CatModel();
        $this->cats = $cm->catTree(1);
        $um = new UserModel();
        $this->users = $um->getAll();
        $whm = new WhModel();
        $this->wh = $whm->getAll();
        $this->sys = Db::table( 'sys' )->find( 1 );

    }

    public function __call( $method, $args ) {
        return '<div style="margin:0 auto;color:red;text-align:center;"><h1>此功能尚未开放!</h1></div>'.$this->back;
    }

    //库存总表
    public function index($page=1){
        $uid=Session::get('logonid');
        if(!$uid) return header('location:/index.php/login');
        $all = Request::param();
        $goods = new GoodsModel();

        $list = Db::table('goods')->where('status',1);
        $query_arr=array(); //分页查询条件设置

        //名称查询
        $name ='';
        if(!empty($all['name'])){
            $name = $all['name'];
            $list = $list->where('name','like','%'.$name.'%');
        }

        $goods_id ='';
        if(!empty($all['goods_id'])){
            $goods_id = $all['goods_id'];
            $list = $list->where('id',$goods_id);
        }
        
        //halt($all);
        $list = $list->order('id')->paginate(15)->toArray();

        foreach($list['data'] as &$v){
            $v['creater_name'] =$this->users[$v['creater']]['name'];
            $v['status_name']=$this->status[$v['status']];
            $v['cat_id_name']=$this->cats[$v['cat_id']]['name'];
            $v['image']=explode(",",$v['image']);
            $tmp=[];
            foreach($v['image'] as &$img){
                if(!$img) continue;
                if($img && substr($img,0,4)!='http'){
                    $tmp[]="http://".$_SERVER['HTTP_HOST'].$img;
                }
            }
            $v['image']=$tmp;

            $v['specs'] = Db::query("select id,name,storage,status from specs where goods_id=".$v['id']);

        }
        //halt($list);
        //处理分页其它参数
        if($name) $query_arr['name']=$name;
        if($goods_id) $query_arr['goods_id']=$goods_id;

        $query="&".http_build_query($query_arr);

        //halt($query);
        View::assign([
            'list'=>$list,
            'name'=>$name,
            'query'=>$query,
            'goods_id'=>$goods_id,
            'goods_list'=>Db::table('goods')->column('id,name')
            ]);

        return View::fetch();

    }


    //库存单据查询
    public function wh_bill() {
        $uid = Session::get( 'logonid' );
        if ( !$uid ) return header( 'location:/index.php/login' );

        $all = Request::param();
        $list = Db::table( 'wh_bill' );

        $status = '';
        if ( !empty( $all[ 'status' ] ) ) {
            $status = $all[ 'status' ];
            $list->where( 'status', $all[ 'status' ] );
        }

        $goods_id = '';
        if ( !empty( $all[ 'goods_id' ] ) ) {
            $goods_id = $all[ 'goods_id' ];
            $list->whereRaw( 'id in(select distinct(bill_id) from wh_list where goods_id =? )', [ $goods_id ] );
        }

        $type = '';
        if ( !empty( $all[ 'type' ] ) ) {
            $type = $all[ 'type' ];
            $list->where( 'type', $all[ 'type' ] );
        }

        $sdate = '';
        if ( !empty( $all[ 'sdate' ] ) ) {
            $sdate = $all[ 'sdate' ];
            $list->where( 'create_time', '>=', trim( $sdate ) );
        }
        $edate = '';
        if ( !empty( $all[ 'edate' ] ) ) {
            $edate = $all[ 'edate' ];
            $list->where( 'create_time', '<=', trim( $edate ) );
        }

        $bill_no = '';
        if ( !empty( $all[ 'bill_no' ] ) ) {
            $bill_no = $all[ 'bill_no' ];
            $list->where( 'bill_no', $all[ 'bill_no' ] );
        }

        $list = $list->order( 'id' )->paginate( 20 )->toArray();

        foreach ( $list[ 'data' ] as &$kv ) {
            $kv[ 'type_name' ] = $this->type[ $kv[ 'type' ] ];
            $kv[ 'status_name' ] = $this->status[ $kv[ 'status' ] ];
            $kv[ 'creater_name' ] = $this->users[ $kv[ 'creater' ] ][ 'name' ];
            $kv[ 'check_name' ] = $this->users[ $kv[ 'creater' ] ][ 'name' ];
        }

        $goods_list = Db::table( 'goods' )->where( 'status', 1 )->column( 'id,name' );
        //select()->toArray();
        //'id,name' );

        $data = [
            'status_arr'=>$this->status,
            'type'=>$type,
            'status'=>$status,
            'bill_no'=>$bill_no,
            'list'=>$list,
            'goods_id'=>$goods_id,
            'goods_list'=>$goods_list,
            'sdate'=>$sdate,
            'edate'=>$edate

        ];

        View::assign( $data );

        return View::fetch();
    }

    //入库操作

    public function wh_inout($type=1,$all=[]) {
        $uid = Session::get( 'logonid' );
        if ( !$uid ) return header( 'location:/index.php/login/target/admin' );

        $all = Request::param();

        if(empty($all['type'])){
            return json(['code'=>0,'msg'=>'出入库单据类型参数缺失!']);
        }else{
            if($all['type']==1){
                $view='wh_in';
            }else{
                $view='wh_out';
            }
        }

        if ( !empty( $all[ 'goods' ] ) ) {

            //处理商品
            $order_list = [];
            $qty = 0;
            $pack_qty = 0;

            $warning=['请注意：库存不足!'];

            foreach ( $all[ 'goods' ] as $goods ) {
                //$goods_db = Db::table( 'goods' )->find( $goods[ 'goods_id' ] );
                $goods[ 'name' ] = $goods[ 'goods_name' ];
                $goods_sp = Db::table( 'specs' )->find( $goods[ 'id' ] );
                $goods[ 'name' ] .= ( '【' . $goods_sp[ 'name' ] . '】' );
                $qty += $goods[ 'qty' ];
                $pack_qty += $goods[ 'pack_qty' ];

                //检测产品库存，如有一项不够就直接退出 
                if($all['type']==2 && $goods['qty']>$goods_sp['storage']){
                    $warning[]=$goods['name'].'出货：'.$goods['qty'].",库存：".$goods_sp['storage'];
                }

                //商品表
                $specs_list[] = array(
                    'goods_id' => $goods[ 'goods_id' ],
                    'name' => $goods[ 'name' ],
                    'specs_id' => $goods[ 'id' ],
                    'pack_qty' => $goods[ 'pack_qty' ],
                    'qty_per_pack'=>$goods[ 'qty_per_pack' ],
                    'qty' => $goods[ 'qty' ],
                    'create_time' => date( 'Y-m-d H:i:s' ),
                    'memo' => $goods[ 'memo' ],
                    'creater' => $uid,
                    'status'=>1
                );
            }
            if(count($warning)>1){
                return json(['code'=>0,'msg'=>implode("<br/>",$warning)]);
            }

            //写出入库单表，产生单号
            $bill_no = 'S'.$all['type']."_".common::randomString( 3 ).date( 'His' );
            $bill_id = Db::table( 'wh_bill' )->insertGetId( [
                'type'=>$all['type'],
                'bill_no'=>$bill_no,
                'qty'=>$qty,
                'pack_qty'=>$pack_qty,
                'status'=>1,
                'creater'=>$uid,
                'create_time'=>date( 'Y-m-d H:i:s' )
            ] );
            //入库单号写入详表中
            foreach ( $specs_list as &$specs ) {
                $specs[ 'bill_id' ] = $bill_id;
            }
            //写入出入库详表
            $res = Db::table( 'wh_list' )->insertAll( $specs_list );

            if ( $res >= 1 ) {
                return json( [ 'code'=>$res, 'msg'=>'OK!' ] );
            } else {
                return json( [ 'code'=>0, 'msg'=>'单据保存失败，请联系管理员!' ] );
            }
        }


        $whs = Db::table( 'warehouse' )->where( 'status', 1 )->select()->toArray();
        $goods = Db::table( 'goods' )->where( 'status', 1 )->column( 'id,name,cat_id,price' );
        $specs = Db::table( 'specs' )->where( 'status', 1 )->column( 'id,name,goods_id,storage' );

        View::assign( [
            'whs'=>$whs,
            'cats'=>$this->cats,
            'goods'=>$goods,
            'specs'=>$specs
        ] ); 
        //halt($this->cats);
        return View::fetch( $view );
    }

    public function wh_list() {
        $uid = Session::get( 'logonid' );
        $all = Request::param();

        //无商品参数提交，表示是进入页面
        if ( empty( $all[ 'id' ] ) || empty( $uid ) ) {
            return json( [ 'code' => 0, 'msg' => '错误，请登录后重试！' ] );
        }

        //halt( $all );
        $bill = Db::table( 'wh_bill' )->find( $all[ 'id' ] );

        $bill[ 'creater_name' ] = $this->users[ $bill[ 'creater' ] ][ 'name' ];
        $bill[ 'check_name' ] = $bill[ 'check' ]? $this->users[ $bill[ 'check' ] ][ 'name' ]:'';
        $bill[ 'type_name' ] = $this->type[ $bill[ 'type' ] ];
        $bill[ 'status_name' ] = $this->status[ $bill[ 'status' ] ][ 0 ];

        $list = Db::table( 'wh_list' )->where( 'bill_id', $all[ 'id' ] )->select()->toArray();

        $pack_sum = 0;
        $qty_sum = 0;
        foreach ( $list as &$kv ) {
            $pack_sum += $kv[ 'pack_qty' ];
            $qty_sum += $kv[ 'qty' ];
            $kv[ 'goods_id_name' ] = Db::table( 'goods' )->where( 'id', $kv[ 'goods_id' ] )->value( 'name' );
            $kv[ 'specs_id_name' ] = Db::table( 'specs' )->where( 'id', $kv[ 'specs_id' ] )->value( 'name' );

        }

        View::assign( [ 'bill' => $bill, 'list' => $list, 'sys' => $this->sys, 'pack_sum' => $pack_sum, 'qty_sum' => $qty_sum ] );

        return View::fetch( 'wh/wh_list' );

    }

    //确认单据，更新库存
    public function wh_check() {
        $uid = Session::get( 'logonid' );
        if ( !$uid ) return json( [ 'code'=>0, 'msg'=>'请登录' ] );

        $all = Request::param();
        if ( empty( $all[ 'id' ] ) ) return json( [ 'code'=>0, 'msg'=>'错误' ] );

        //id:出入库单据id
        $bill = Db::table( 'wh_bill' )->find( $all[ 'id' ] );
        if ( $bill[ 'status' ] != 1 ) return json( [ 'code'=>0, 'msg'=>'状态不正确' ] );

        //遍历单据详情表，更新对应商品的库存
        $list = Db::table( 'wh_list' )->where( 'bill_id', $bill[ 'id' ] )->select()->toArray();
        $res = 0;
        foreach ( $list as &$item ) {
            if ( $bill[ 'type' ] == 2 ) {
                $item[ 'qty' ] = -$item[ 'qty' ];
            }
            $item[ 'before_storage' ] = Db::table( 'specs' )->where( 'id', $item[ 'specs_id' ] )->value( 'storage' );
            $item[ 'after_storage' ] = $item[ 'before_storage' ]+ $item[ 'qty' ];
            Db::table( 'specs' )->save( [ 'id'=>$item[ 'specs_id' ], 'storage'=>$item[ 'after_storage' ] ] );
            $res += Db::table( 'wh_list' )->save( $item );
            //更新商品的期初末库存
        }
        //单据本身的状态
        Db::table( 'wh_bill' )->save( [ 'id'=>$all[ 'id' ], 'status'=>2, 'check'=>$uid, 'check_time'=>date( 'Y-m-d H:i:s' ) ] );

        return json( [ 'code'=>$res ] );

    }

    //库存进出明细查询

    public function wh_query() {
        $uid = Session::get( 'logonid' );
        $all = Request::param();
        // halt( $all );

        //无商品参数提交，表示是进入页面
        if ( empty( $uid ) ) {
            return json( [ 'code' => 0, 'msg' => '错误，请登录后重试！' ] );
        }

        $list = Db::table( 'wh_list' );

        $goods_id = '';
        if ( !empty( $all[ 'goods_id' ] ) ) {
            $goods_id = $all[ 'goods_id' ];
            $list->where( 'goods_id', $goods_id );
        }
        $specs_id = '';
        if ( !empty( $all[ 'specs_id' ] ) ) {
            $specs_id = $all[ 'specs_id' ];
            $list->where( 'specs_id', $specs_id );
        }
        $sdate = '';
        if ( !empty( $all[ 'sdate' ] ) ) {
            $sdate = $all[ 'sdate' ];
            $list->where( 'create_time', '>=', trim( $sdate ) );
        }
        $edate = '';
        if ( !empty( $all[ 'edate' ] ) ) {
            $edate = $all[ 'edate' ];
            $list->where( 'create_time', '<=', trim( $edate ) );
        }

        $list = $list->order( 'id' )->paginate( 20 )->toArray();
        foreach ( $list[ 'data' ] as &$kv ) {
            $kv[ 'goods_id_name' ] = Db::table( 'goods' )->where( 'id', $kv[ 'goods_id' ] )->value( 'name' );
            $kv[ 'specs_id_name' ] = Db::table( 'specs' )->where( 'id', $kv[ 'specs_id' ] )->value( 'name' );
            $kv[ 'bill_no' ] = Db::table( 'wh_bill' )->where( 'id', $kv[ 'bill_id' ] )->value( 'bill_no' );
        }

        View::assign( [
            'specs_id'=>$specs_id,
            'specs_list'=>Db::table( 'specs' )->where( 'status', 1 )->column( 'id,name,goods_id' ),
            'goods_id'=>$goods_id,
            'goods_list'=>Db::table( 'goods' )->where( 'status', 1 )->column( 'id,name' ),
            'sys'=>$this->sys,
            'list'=>$list
        ] );
       // halt( $list );
        return View::fetch( 'wh_query' );

    }

    //订单删除

    public function wh_cancel( $id = '' ) {
        $uid = Session::get( 'logonid' );
        if ( empty( $uid ) )
        return json( [ 'code' => 0, 'msg' => '登录已过期' ] );

        $all = Request::param();

        if ( empty( $all[ 'id' ] ) || empty( $all[ 'table' ] ) ) {
            return json( [ 'code' => 0, 'msg' => '参数不正确' ] );
        }

        $res = common::row_del( $all[ 'table' ], $all[ 'id' ], '出入库单据', 'wh_list|bill_id' );

        return $res;
    }

}
